package com.cloudOffice.interceptor;

import com.alibaba.fastjson.JSON;
import com.cloudOffice.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @program: cloud-office
 * @className: ResponseBodyInterceptor
 * @description: 响应拦截器
 * @data: 2024/2/11 19:59
 * @author: ihu
 * @version: 1.0
 **/

@Slf4j
@RestControllerAdvice
public class ResponseBodyInterceptor implements ResponseBodyAdvice<Object> {
	@Override
	public boolean supports(MethodParameter returnType, Class converterType) {
		return returnType.getParameterType().isAssignableFrom(Result.class);
	}
	
	@Override
	public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
	                              Class selectedConverterType, ServerHttpRequest request,
	                              ServerHttpResponse response) {
		log.info("请求返回数据：body: {}", JSON.toJSONString(body));
		// 取出响应结果，修改状态码
		if (body != null) {
			int code = ((Result<?>) body).getCode();
			log.info("响应拦截器：code: {}", code);
			if (code != 200) {
				response.setStatusCode(HttpStatus.valueOf(code));
			}
		}
		return body;
	}
}
